package com.teaching.Controller;

import com.alibaba.fastjson.JSONObject;
import com.teaching.Dao.CourseDaoAchieve;
import com.teaching.Dao.LearnDao;
import com.teaching.Dao.LearnDaoAchieve;
import com.teaching.Dao.ScoreDaoAchieve;
import com.teaching.Enity.Course;
import com.teaching.Enity.Learn;
import com.teaching.Enity.Score;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
public class AddController {

    @PostMapping(value = "/chooseCourse",produces = "application/json; charset=UTF-8")//学生选课
    public boolean chooseCourse(@RequestBody JSONObject jsonObject) throws IOException {
        System.out.println(jsonObject.toJSONString());
        int c_id = jsonObject.getInteger("c_id");
        int s_id = jsonObject.getInteger("s_id");
        CourseDaoAchieve courseDaoAchieve = new CourseDaoAchieve();
        List<Course> courseList = courseDaoAchieve.findStudentCourse(s_id);
        for (int i=0;i<courseList.size();i++){
            if (c_id==courseList.get(i).getId()){
                return false;
            }
        }
        LearnDaoAchieve learnDaoAchieve = new LearnDaoAchieve();
        Learn learn = new Learn();
        learn.setC_id(c_id);
        learn.setS_id(s_id);
        learnDaoAchieve.ChooseCourse(learn);
        return true;
    }

    @PostMapping(value = "/addScore",produces = "application/json; charset=UTF-8")//成绩录入
    public boolean addScore(@RequestBody JSONObject jsonObject) throws IOException{
        int c_id = jsonObject.getInteger("c_id");
        int s_id = jsonObject.getInteger("s_id");
        int grade = jsonObject.getInteger("grade");

        ScoreDaoAchieve scoreDaoAchieve = new ScoreDaoAchieve();
        LearnDaoAchieve learnDaoAchieve = new LearnDaoAchieve();
        Learn learn = new Learn();
        learn.setS_id(s_id);
        learn.setC_id(c_id);
        List<Score> scoreList = scoreDaoAchieve.AllScore();
        List<Learn> learnList = learnDaoAchieve.GetSc_id(learn);
        if (learnList.size()==0){
            return false;
        }

        for (int i=0;i<scoreList.size();i++){
            if (scoreList.get(i).getSc_id()==learnList.get(0).getId()){
                return false;
            }
        }

        Score score = new Score();
        score.setGrade(grade);
        score.setSc_id(learnList.get(0).getId());
        scoreDaoAchieve.AddScore(score);
        return true;
    }
}
